package day03;

public class Fraction implements Comparable<Fraction> {

    protected long top;
    protected long bottom;


    public Fraction(long top) {
        this(top, 1);
    }

    public Fraction() {
        this(0);
    }

    public Fraction(long top, long bottom) {

        this.top = top;
        this.bottom = bottom;
        this.rationalize();
    }

    private void rationalize() {
        int flag = 1;
        if ((long) top * bottom < 0) flag = -1;
        if (top < 0) top = -top;
        if (bottom < 0) bottom = -bottom;
        long gcd = MathTools.gcd(top, bottom);
        top /= gcd;
        bottom /= gcd;
        top *= flag;
    }

    @Override
    public String toString() {
        return top + "/" + bottom;
    }


    public Fraction add(Fraction that) {
        Fraction result = new Fraction();
        result.top = this.top * that.bottom + that.top * this.bottom;
        result.bottom = this.bottom * that.bottom;
        result.rationalize();
        return result;
    }

    @Override
    public int compareTo(Fraction that) {
        Double thisDoubleValue = this.doubleValue();
        Double thatDoubleValue = that.doubleValue();
        return thisDoubleValue.compareTo(thatDoubleValue);

    }

    public double doubleValue() {
        return (double) top / bottom;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Fraction)) return false;
        Fraction that = (Fraction) obj;
        return this.compareTo(that) == 0;


    }

    // 1/2
    public static Fraction parsFraction(String str) {
        int pos = str.indexOf('/');
        if (pos < 0) return new Fraction();//TODO;
        long top = Long.parseLong(str.substring(0, pos));
        long bottom = Long.parseLong(str.substring(pos + 1));
        return new Fraction(top, bottom);
    }
}


